import numpy as np
import csv
import random
from datetime import datetime
from time import strftime


def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = np.array([])
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey =np.append(sKey, temp)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey


#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "begin at " + getCurTime()
    
    unitCSV = "C:/Documents and Settings/wang322/My Documents/Downloads/WelFlows_3_coid.csv"
    dataMatrix = build_data_list(unitCSV)
    #coorCSV = "C:/Documents and Settings/wang322/My Documents/Downloads/WelFlows_2_unique_co.csv"
    #coordinate = build_data_list(coorCSV)
    print dataMatrix[0]
    iLen = dataMatrix.shape
    output = np.array([])
    i = 0
    for item in dataMatrix:
        if (i+1) < iLen[0]:
            if dataMatrix[i+1,0] == item[0]:
                output = np.append(output, [item[0], item[-1], dataMatrix[i+1,-1], item[6], item[7], item[8], item[9]])
        i += 1
    #print output[0:]
    output.shape = (-1, 7)
    #for item in unit_attri:
        #for coor in coordinate:
            #if(item[3] == coor[1]) & (item[4] == coor[2]):
                #item[-1] = coor[0]
                #break
    #coordinate = np.array([])
    #x = np.unique(dataMatrix[:,3])
    #y = np.unique(dataMatrix[:,4])
    #print x, y
    #for item in unit_attri:
    #for item_x in x:
        #for item_y in y:
            #for item in unit_attri:
                #if (item[3] == item_x) & (item[4] == item_y):
                    #coordinate = np.append(coordinate, [item_x, item_y])
                    #break

    #coordinate.shape = (-1, 2)
    
        
        


    #print riskarea_attri
    
    filePath = unitCSV[:-4] + "_output.csv"
    np.savetxt(filePath, output, delimiter=',')

    print "end at " + getCurTime()
    print "========================================================================"  

           
